<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <!--顶部栏-->
    <el-menu
            :default-active="activeIndex1"
            class="el-menu-demo"
            mode="horizontal"
            background-color="#545c64"
            text-color="#fff"
            style="text-align: right"
            active-text-color="#ffd04b">
        <el-menu-item index="1">我的购物车</el-menu-item>
        <el-menu-item index="2" v-if="flag">欢迎{{username}}</el-menu-item>
        <el-menu-item index="3" v-if="flag"><a href="#" @click="logout">注销</a></el-menu-item>
        <el-menu-item index="2" v-if="!flag">
            请先<a href="login.html">登陆</a>
        </el-menu-item>
        <el-menu-item index="3" v-if="!flag">
            没有账号，那就<a href="register.html">注册</a>
        </el-menu-item>
    </el-menu>
    <!--我的购物车-->
    <div class="cart-container">
        <el-table :data="cartItems" style="width: 100%"
                  @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column prop="bookName" label="商品名称" width="180"></el-table-column>
            <el-table-column prop="price" label="单价" width="180"></el-table-column>
            <el-table-column label="数量" width="200">
                <template slot-scope="scope">
                    <el-input-number
                            v-model="scope.row.number"
                            :min="1"
                            @change="(current,old)=>changeCartNumber(current,old,scope.row)">
                    </el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="小计">
                <template slot-scope="scope">
                    {{ (scope.row.price * scope.row.number).toFixed(2) }}
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot="header" slot-scope="scope">
                    <el-button type="danger" plain icon="el-icon-delete" @click="deleteBatch">删除选中</el-button>
                    <el-button type="danger" plain icon="el-icon-delete" @click="deleteAll">清空购物车</el-button>
                </template>
                <template slot-scope="scope">
                    <el-button
                            type="danger"
                            @click="deleteById(scope.row)"
                            icon="el-icon-delete">
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="total-price" style="text-align: right">
            总计：¥{{ totalPrice.toFixed(2) }}
        </div>

        <div style="text-align: right">
            <el-button type="primary" class="checkout-btn">去结算</el-button>
        </div>
    </div>
</div>
</body>
</html>
<script src="js/vue.min.js"></script>
<script src="js/axios.min.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                activeIndex1: 1,
                token: localStorage.getItem('token'),
                username: '',
                flag: true,
                cartItems: [],
                selectCartItems: []
            }
        },
        methods: {
            logout() {
                axios({
                    method: 'get',
                    url: 'users',
                    params: {
                        method: 'logout'
                    }
                }).then(resp => {
                    if (resp.data.success) {
                        localStorage.removeItem('token')
                        this.flag = false
                        this.username = ''
                        this.token = null
                    }
                })
            },
            loadCartsData() {
                axios({
                    url: 'carts',
                    params: {
                        method: 'find_user_id',
                        url: 'carts'
                    }
                }).then(resp => {
                    this.cartItems = resp.data.data
                })
            },
            changeCartNumber(current_number, old_number, row) {

                let data = new URLSearchParams()
                data.append('method', 'change_cart_number')
                data.append('book_id', row.bookId)
                data.append('number', current_number - old_number)
                axios({
                    method: 'post',
                    url: 'carts',
                    data: data
                }).then(resp => {
                    if (!resp.data.success) {
                        // this.loadCartsData()
                        row.number = old_number
                        this.$message({
                            message: '更新购物车失败',
                            type: 'error',
                            duration: 2000
                        });
                    }
                })
            },
            deleteById(row) {
                this.$confirm('此操作将永久从购物车中删除' + row.bookName + ', 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    axios({
                        method: 'delete',
                        url: 'carts',
                        params: {
                            method: 'delete_by_id',
                            id: row.id
                        }
                    }).then(resp => {
                        if (resp.data.success) {
                            this.loadCartsData()
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            return
                        }
                        this.$message({
                            type: 'error',
                            message: '删除失败'
                        });
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleSelectionChange(val) {
                this.selectCartItems = val
            },
            deleteBatch() {
                this.$confirm('此操作将永久从购物车中删除选中的数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = ''
                    for (let i = 0; i < this.selectCartItems.length; i++) {
                        let item = this.selectCartItems[i];
                        ids += item.id + ','
                    }
                    ids = ids.substring(0, ids.length - 1)
                    axios({
                        method: 'delete',
                        url: 'carts',
                        params: {
                            ids: ids,
                            method: 'delete_by_batch'
                        }
                    }).then(resp => {
                        if (resp.data.success) {
                            this.loadCartsData()
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            return
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });


            },
            deleteAll() {
                if (this.cartItems.length <= 0) {
                    this.$message({
                        type: 'error',
                        message: '购物车不存在'
                    });
                    return
                }
                this.$confirm('此操作将永久清空购物车的数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios({
                        url: 'carts',
                        method: 'delete',
                        params: {
                            method: 'delete_all'
                        }
                    }).then(resp => {
                        if (resp.data.success) {
                            this.loadCartsData()
                            this.$message({
                                type: 'success',
                                message: '已成功删除'
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }

        },
        computed: {
            totalPrice() {
                return this.selectCartItems.reduce((total, item) => {
                    return total + (item.price * item.number)
                }, 0)
            }
        },
        created() {
            this.loadCartsData()
            // 登陆的内容
            if (this.token === null || this.token === undefined) {
                this.flag = false
            } else {
                this.flag = true
                this.username = JSON.parse(this.token).username
            }
        }
    })
</script>